<?php


class core
{
    public static function initialize(): void
    {
//        include("/system/core/core.phar");
        self::loadComponent("define");
        if (json_decode(file_get_contents(CONFIG_PATH."global_config.json"),true)["proxy"]=="yes") {
            define("PROXY_CODE", $_GET["PROXY_CODE"]);
            unset($_GET["PROXY_CODE"]);
        }
        self::loadComponent("encryptTool");
        self::loadComponent("cookie");
        self::loadComponent("language");
        self::loadComponent("get");
        self::loadComponent("post");
        self::loadComponent("dbTool");
        self::loadComponent("fileDBTool");
        self::loadComponent("mysqlTool");
        self::loadComponent("argsTool");
        self::loadComponent("arrayTool");
        self::loadComponent("phpIniTool");
        self::loadComponent("zipTool");
//        self::loadComponent("dbAdmin");
        date_default_timezone_set("PRC");

//        echo self::getPath();
//        session_start();
//        $_SESSION["test"] = "test";
//        self::debugMessage("调试","存储Cookie");
//        cookie::set("test","test");

        /*cookie::set("isLogin","yes")
            ->set("username","schlibra")
            ->set("nickname","SCH小斯")
            ->set("room_xcid","chat")
            ->set("password-part1", "")
            ->set("password-part2", "")
            ->set("password-part3", "")
            ->set("password-part4", "")
            ->set("isAdmin","yes");*/


    }

    public static function runWeb(): void
    {
        $rm = strtolower($_SERVER["REQUEST_METHOD"]);
        $path = substr(self::getPath(), 1);
        if (!$path) {
            $path = "index";
        }
        if ($rm == "get") {
            if (@file_get_contents(HTML_PATH . $path . ".html")) {
                get::load($path);
                /*if (!call_user_func($rm."::".$path)){
    //                get::oneKeyLoad($path);
                }*/
            } else {
                self::loadErrorPage("404 Not Found", "找不到你要访问的页面或资源");
            }
        } elseif ($rm == "post") {
//            echo function_exists("post::login")?"yes":"no";
//            if (function_exists("post::" . $path)) {
//                call_user_func($rm . "::" . $path);
//            } else {
//                die("404 not fount:找不到你要访问的页面或资源");
//            }
            $path = str_replace("/","",$path);
            if (!@call_user_func("post::$path")) {
                die("404 not fount:找不到你要访问的页面或资源");
            }
        }
//    call_user_func($rm . "::" . $path);
    }

    public static function getPath(): string
    {
        $a = "/";//未加参数的情况
        if (isset($_SERVER['QUERY_STRING'])) {//指定地址参数时
            $a = $_SERVER['QUERY_STRING'];//读取请求参数的内容
        }
        $b = stripos($a, "&");//获取&符号第一次出现位置
        if ($b != "") {
            $c = substr($a, 0, $b);//获取第一参数
        } else {
            $c = $a;//未加参数时返回/
        }
        if ($c == "") {
            $c = "/";//参数为空时返回/
        }
        if (substr($c, strlen($c) - 1, 1) == "/") {
            $c = substr($c, 0, strlen($c) - 1);//若地址最后存在一个/，将删除这个/
        }
        if ($c == "") {
            $c = "/";//地址未空时变为/
        }
        if (substr($c, 0, 1) != "/") {
            header("Location:./?/");
        }
        return $c;//返回地址
    }

    public static function loadComponent(string $name): void
    {
        if (file_exists("debug")) {//调试模式
            $component_path = "src/core/$name.php";
        } else {
            $component_path = "phar://core.phar/$name.php";
        }

        /*if (defined("CORE_PATH")) {
            $component_path = CORE_PATH . $name . ".php";
        } else {
            if (file_exists("./system/core/define.php")) {
                $component_path = "system/core/dev/$name.php";
            }else{
                $component_path = "phar://core.phar/$name.php";
            }
        }
        if (defined("DEBUG")&&DEBUG=="yes"){
            $component_path = "./system/core/dev/$name.php";
        }else{
            $component_path = "phar://core.phar/$name.php";
        }*/
//        echo $component_path."<br>";
//        echo "loading <mark>$name</mark> component...";
        if (file_exists($component_path)) {
            include($component_path);
//            echo "<mark>$name</mark> component load successful!<br>";
        } else {
            self::loadErrorPage("网站加载失败", "<b style='color: red'>没有找到组件：" . $name . "</b>");
            die();
        }
    }

    public static function loadHead(string $title, array $extraFile = null): void
    {
        $value = file_get_contents(HTML_PATH . "head.html");//读取头部文件
        $value = str_replace("{TITLE}", $title, $value);//设置标题
        $extraFileText = "";
        if ($extraFile) {
            if (isset($extraFile["js"])) {
                $js = $extraFile["js"];
                for ($i = 0; $i < count($js); $i++) {
                    if (substr($js[$i], 0, 7) === "http://" || substr($js[$i], 0, 8) === "https://" || substr($js[$i], 0, 2) === "//") {
                        $extraFileText .= "<script src='" . $js[$i] . "'></script>";
                    } else {
                        $extraFileText .= "<script src='" . JS_PATH . $js[$i] . ".js'></script>";
                    }
                }
            }
            if (isset($extraFile["css"])) {
                $css = $extraFile["css"];
                for ($i = 0; $i < count($css); $i++) {
                    $t = $css[$i];
                    if (is_string($t)) {
                        $extraFileText .= "<link href='" . CSS_PATH . $t . ".css' rel='stylesheet' type='text/css'>";
                    } elseif (is_array($t)) {
                        $extraFileText .= "<link href='" . CSS_PATH . $t[0] . ".css' rel='stylesheet' type='text/css' " . $t[1] . ">";
                    }
                }
            }
            if (isset($extraFile["mobile"])) {
                if ($extraFile["mobile"] == "yes") {
                    $extraFileText .= '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">';
                }
            }
        }
        $value = str_replace("{extraFile}", $extraFileText, $value);
        $value = self::link_process($value);
        echo "<html lang='" . LOCAL_LANGUAGE . "'>";
        echo $value;
    }

    public static function loadBody(string $name, array $args = null): void
    {
        $value = file_get_contents(HTML_PATH . $name . ".html");
        if ($args) {
            for ($i = 0; $i < count($args); $i++) {
                $key = array_keys($args)[$i];
                $value = str_replace("{" . $key . "}", $args[$key], $value);
            }
        }
        $value = self::link_process($value);
        echo $value;
    }

    public static function loadBodyByText(string $content, array $args = null): void
    {
        $value = $content;
        if ($args) {
            for ($i = 0; $i < count($args); $i++) {
                $key = array_keys($args)[$i];
                $value = str_replace("{" . $key . "}", $args[$key], $value);
            }
        }
        $value = self::link_process($value);
        echo $value;
    }

    public static function loadErrorPage(string $title, string $message): void
    {
        self::loadHead($title);
        self::loadBody("error", ["ERROR_TITLE" => $title, "ERROR_CONTENT" => $message]);
    }

    public static function link_process(string $input): string
    {
        $value = $input;
        $index = 0;
        $args_list = array();
        $args_index = 0;
        $left = false;
        $value = str_replace("{nav}", file_get_contents(HTML_PATH . "nav.html"), $value);
        $value = str_replace("{FriendLinks}",self::loadFriendLink(),$value);
        $value = str_replace("{LanguageList}",self::loadLanguageList(),$value);
        $value = str_replace("{VERSION}",VERSION,$value);
//        $value = str_replace("{UserList}",json_encode(arrayTool::removeFirst(dbTool::select("user",["*"],["*"])["data"])),$value);
        $value = str_replace("{DEBUG}",argsTool::get("DEBUG"),$value);
        $value = str_replace("{ID}",argsTool::get("id"),$value);
        for ($i = 0; $i < count(L); $i++) {
            $key = array_keys(L)[$i];
            $value = str_replace("{TEXT_" . $key . "}", L[$key], $value);
        }
        $language_list = json_decode(file_get_contents(LANG_PATH . "languages.json"));
        $language_list_data = "";
        foreach ($language_list as $language) {
            $language_name = explode("=", explode("\n", str_replace("\r", "", file_get_contents(LANG_PATH . $language . ".lang")))[0])[1];
            $language_list_data .= '<li><a data-language="' . $language . '" class="lang">' . $language_name . '</a></li>';
        }
        $value = str_replace("{language_list}", $language_list_data, $value);
        while (true) {
            $t = substr($value, $index, 1);
            $index++;
            if ($t === "{") {
                $left = true;
                continue;
            }
            if ($t === "}") {
                $left = false;
                $args_index++;
            }
            if ($left) {
                if ($t === " " || $t === "\r" || $t === "\n") {
                    $left = false;
                    continue;
                }
                @$args_list[$args_index] .= $t;
            }
            if ($index === strlen($value)) {
                break;
            }
        }
        foreach ($args_list as $item) {
            $x = explode("_", $item);
            if ($x[0] === "IMG") {
                $value = str_replace("{" . $item . "}", IMG_PATH . $x[1] . "." . $x[2], $value);
            } elseif ($x[0] === "LINK") {
                $path = substr($x[1], 0, 1) === "/" ? $x[1] : "/" . $x[1];
                $rewrite = json_decode(file_get_contents(CONFIG_PATH."global_config.json"),true)["rewrite"]=="yes";
                if ($path=="/index"){
                    $path = "/";
                }
                if ($rewrite){//是否开启伪静态
                    $value = str_replace("{" . $item . "}",$path,$value);
                }else {
                    $value = str_replace("{" . $item . "}", "./?" . $path, $value);
                }
            } elseif ($x[0] === "JS") {
                $value = str_replace("{" . $item . "}", JS_PATH . $x[1] . ".js", $value);
            } elseif ($x[0] === "MEDIA") {
                $value = str_replace("{" . $item . "}", MEDIA_PATH . $x[1] . "." . $x[2], $value);
            } elseif ($x[0] === "AUDIO") {
                $value = str_replace("{" . $item . "}", AUDIO_PATH . $x[1] . "." . $x[2], $value);
            } elseif ($x[0] === "FONT") {
                $value = str_replace("{" . $item . "}", FONT_PATH . $x[1] . "." . $x[2], $value);
            } elseif ($x[0] === "COOKIE") {
                $value = str_replace("{" . $item . "}", cookie::get($x[1]), $value);
            }
        }
        return $value;
    }

    public static function clearConsole(): void
    {
        echo "<script>console.clear();</script>";
    }

    public static function debugMessage(string $label, string $message, bool $die = false): void
    {
        $time = date("m-d H:i");
        echo "[$time $label] $message<br>";
        if ($die) die();
    }

    public static function loadFriendLink():string
    {
        $result = "";
        if (file_exists(CONFIG_PATH . "friend_links.json")) {
            $a = file_get_contents(CONFIG_PATH . "friend_links.json");
            $b = json_decode($a, true);
            foreach (array_keys($b) as $x) {
                $t = $b[$x];
                $target = "";
                switch ($t['openWay']) {
                    case "this":
                    case "thisTab":
                    case "self":
                        $target = "_self";
                        break;
                    case "parent":
                        $target = "_parent";
                        break;
                    case "top":
                        $target = "_top";
                        break;
                    case "new":
                    case "newTab":
                    case "blank":
                    default:
                        $target = "_blank";
                        break;
                }
                if (!(isset($t['hide']) && $t['hide'])) {
                    $result .= "<li><a target='$target' href='" . $t['link'] . "'>" . $t['name'] . "</a></li>";
                }
            }
        }
        return $result;
    }

    public static function loadLanguageList():string
    {
        $result = "";
        for ($i = 0; $i < count(LANGUAGE_LIST); $i++) {
            $result .= '<li><a href="{LINK_setLang}&lang=' . array_keys(LANGUAGE_LIST)[$i] . '&from=' . self::getPath() . (isset($_GET['step'])?(',step='.$_GET['step']):'').'">' . LANGUAGE_LIST[array_keys(LANGUAGE_LIST)[$i]] . '</a></li>';
        }
        return $result;
    }

    public static function xc_mail($address, $subject, $body):array
    {
        $result = array();
        $wait_time = 180;
        if (time() - cookie::get('send_mail_time') < $wait_time) {
//        $a = time();
//        $b = cookie::get('send_mail_time');
            $c = $wait_time - (time() - cookie::get('send_mail_time'));
            $result['status'] = "send_wait";
            $result['wait_time'] = $c;
            return $result;
        }
        require './src/mail/PHPMailerAutoload.php';
        $config = json_decode(file_get_contents(CONFIG_PATH . "mail_config.json"), true);
        $mail = new PHPMailer(false);
        $mail->isSMTP();
        $mail->Host = $config['mail_smtp'];
        $mail->SMTPAuth = true;
        $mail->Username = $config['mail_username'];
        $mail->Password = $config['mail_password'];
        try {
            $mail->setFrom($config['mail_username'], L['ROOT_TITLE']);
        } catch (phpmailerException $e) {
        }
        $mail->addAddress($address);
        $mail->CharSet = 'UTF-8';
        $mail->Subject = $subject;
        $mail->isHTML();
        $mail->Body = str_replace("{body}", $body, '<div style="width: 85%;height: 50%;padding: 15px;background-color: #3280fc;color: #FFFFFF;box-shadow: 10px 10px 5px grey;font-size: 25px">{body}</div>');
        $mail->AltBody = L['MAIL_ALTBODY'];
        try {
            if ($mail->send()) {
                cookie::set("send_mail_time", time());
                $result['status'] = "successful";
            } else {
                $result['status'] = "fail";
                $result['reason'] = $mail->ErrorInfo;
            }
        } catch (phpmailerException $e) {
        }
        return $result;
    }
}